<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :is-show="true">
        <span slot="before">共{{ total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button v-if="checkBtn('addEmployee')" size="small" type="primary" @click="addEmployee">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="employeeList">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="头像" sortable="" width="200px">
            <template #default="{row}">
              <img
                v-fixImg="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                alt=""
                style="width:180px;height:120px"
                @click="showCodeFn(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployee" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template #default="obj">
              {{ obj.row.timeOfEntry |formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template #default="obj">
              <!-- {{ obj.row.enableState }} -->
              <el-switch v-model="obj.row.enableState" :active-value="1" :inactive-value="2" disabled />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="employee">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${employee.row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showRoleFn(employee.row.id)">角色</el-button>
              <el-button
                v-if="checkBtn('delEmployee')"
                type="text"
                size="small"
                @click="delEmployee(employee.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination layout="prev, pager, next" :total="total" :page-size="pageConfig.size" @current-change="currentChange" />
        </el-row>
      </el-card>
    </div>
    <addEmployeeDialog
      :show-dialog="showDialog"
      @closeDidlog="closeDidlog"
    />
    <!-- 角色弹出框 -->
    <assgin-role ref="assignRole" :is-show-dialog.sync="isShowRole" />
    <el-dialog title="二维码" :visible="isShowCode" @close="isShowCode = false">
      <el-row>
        <canvas ref="canvas" />
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getEmployeeInfoList, delEmployee } from '@/api/employee'
import addEmployeeDialog from './addEmployee'
import employeeConstant from '@/api/constant'
import { export_json_to_excel } from '@/vendor/export2excel'
import { formatDate } from '@/filters'
import QRCode from 'qrcode'
import AssginRole from './components/assgin-role.vue'
export default {
  components: { addEmployeeDialog, AssginRole },
  // 局部定义的过滤器
  // filters: {
  //   formatDate(oldVal) {
  //     return oldVal.split('T')[0]
  //   }
  // },
  data() {
    return {
      isShowRole: false,
      isShowCode: false,
      pageConfig: {
        page: 1,
        size: 5
      },
      employeeList: [],
      total: 0,
      showDialog: false
    }
  },
  created() {
    // 页面初始化
    this.getEmployeeInfoList()
  },
  methods: {
    // 校验按钮权限  可通过全局混入mixin 合并methods
    // checkBtn(btnName) {
    //   // const roles = this.$store.state.user.userInfo.roles
    //   // return roles && roles.points.includes(btnName)

    //   // 可选链方式(ie不支持)
    //   return this.$store.state.user.userInfo.roles?.points.includes(btnName)
    // },

    // 角色弹出
    async showRoleFn(id) {
      await this.$refs.assignRole.getUserInfo(id)
      this.isShowRole = true
    },
    // 展示二维码
    showCodeFn(url) {
      if (url) {
        this.isShowCode = true
        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.canvas, url)
        })
      }
    },
    // 导出excel表格
    async exportExcel() {
      // 请求所有员工信息
      const { rows } = await getEmployeeInfoList({ page: 1, size: this.total })
      // console.log(rows)
      const header = ['手机号', '姓名', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      // 对数据进行处理，rows为二维数组
      const data = this.objToArr(rows)
      // console.log(92, data)
      // 调用导出函数
      await export_json_to_excel({ header, data })
      // this.$message.success('导出成功')
    },
    // 将[{}]转化为[[]]的函数
    objToArr(data) {
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const newArr = []
      // 将对象数组转化为二维数组
      data.forEach(item => {
        const tempArr = []
        // 遍历字典对象，对中文key进行替换
        for (const key in dict) {
          const enkey = dict[key]
          let value
          if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
            // 对时间数据进行格式化（从过滤器中直接导出方法使用）
            value = formatDate(item[enkey])
          } else if (enkey === 'formOfEmployment') {
            // 对聘用形式进行处理
            const obj = employeeConstant.formOfEmployment.find(res => Number(res.id) === Number(item[enkey]))
            value = obj ? obj.val : '未知'
          } else {
            // 一般数据直接赋值
            value = item[enkey]
          }
          // 将值添加到数组里
          tempArr.push(value)
        }
        // 将临时数组添加到新数组里
        newArr.push(tempArr)
      })
      return newArr
    },
    // 获取员工基本信息列表
    async getEmployeeInfoList() {
      const res = await getEmployeeInfoList(this.pageConfig)
      this.employeeList = res.rows.map(item => {
        // 处理账户状态，部分数据没有该字段。
        const state = Math.round(Math.random())
        return { ...item, enableState: item.enableState || state }
      })
      console.log(this.employeeList)
      this.total = res.total
    },
    // 页面切换时触发
    currentChange(newPage) {
      this.pageConfig.page = newPage
      this.getEmployeeInfoList()
    },
    // 删除员工信息
    async delEmployee(id) {
      await this.$confirm('是否确认删除？')
      await delEmployee(id)
      this.$message.success('删除成功！')
      // 判断是否是当前页最后一条。是的话更新后就是上一页
      if (this.employeeList.length === 1 && this.pageConfig.page > 1) {
        this.pageConfig.page--
      }
      this.getEmployeeInfoList()
    },
    // 新增员工
    addEmployee() {
      this.showDialog = true
    },
    closeDidlog() {
      this.showDialog = false
    },
    // 格式化员工聘用形式
    formatEmployee(row, column, cellValue, index) {
      const obj = employeeConstant.formOfEmployment.find(item => item.id === cellValue)
      return obj ? obj.val : '未知'
    }
  }
}
</script>
<style lang="scss" >
img{
  object-fit: cover;
}
</style>
